package com.wngbms.netty.seatdemo.service;

import com.alibaba.fastjson.JSON;
import com.wngbms.netty.seatdemo.bean.OwnerInfo;
import com.wngbms.netty.seatdemo.comm.*;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatInMessage;
import com.wngbms.netty.seatdemo.message.SeatOutMessage;
import com.wngbms.netty.seatdemo.server.SeatBizHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class OwnerSearchHandler implements SeatTypeHandler {
    public static final CmdType CMD_TYPE = CmdType.OWNER_SEARCH;

    @Override
    public void handleInbound(SeatInMessage seatInMessage) {
        log.info("业主查询请求");

        OwnerInfo ownerInfo = findOwner();
        byte[] bodyBytes = JSON.toJSONString(ownerInfo).getBytes(StandardCharsets.UTF_8);

        BaseHeader baseHeader = BaseHeader.build(MagicVersion.V1,
                CmdType.OWNER_SEARCH, BodyType.JSON,
                EncryptionType.NON, ReqOrResp.RESP, bodyBytes.length);

        ChannelHandlerContext channelHandlerContext = seatInMessage.getChannelHandlerContext();
        Channel channel = channelHandlerContext.channel();
        SeatOutMessage seatOutMessage = new SeatOutMessage();
        seatOutMessage.setBaseHeader(baseHeader);
        seatOutMessage.setBody(bodyBytes);

        channel.writeAndFlush(seatOutMessage);

        sleep(1000);
        String userId = SeatBizHandler.USER_SOCKET_MAP.get(channel.remoteAddress());
        HandleFactory.getHandler(CmdType.HANGUP).handleOutbound(userId);
    }

    public OwnerInfo findOwner() {
        OwnerInfo ownerInfo = new OwnerInfo();
        ownerInfo.setPersonId(1099L);
        ownerInfo.setName("王力宏");
        ownerInfo.setMobile("13321444152");
        return ownerInfo;
    }
}
